package libofei.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (value != null) {
            value = xssEncode(value);
        }

        return value;
    }

    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (parameters != null && parameters.length != 0) {
            for(int i = 0; i < parameters.length; ++i) {
                parameters[i] = xssEncode(parameters[i]);
            }

            return parameters;
        } else {
            return null;
        }
    }

    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (value != null) {
            value = xssEncode(value);
        }

        return value;
    }

    private static String xssEncode(String s) {
        if (s != null && !s.isEmpty()) {
            s = s.replaceAll(">", "＞");
            s = s.replaceAll("<", "＜");
            s = s.replaceAll("'", "＇");
            return s;
        } else {
            return s;
        }
    }
}

